
import os

def convert_to_utf8(file_path):
    try:
        # 尝试以不同编码读取文件
        with open(file_path, 'rb') as f:
            content = f.read()
        
        # 尝试检测文件编码
        try:
            import chardet
            detected = chardet.detect(content)
            encoding = detected['encoding']
        except ImportError:
            # 如果没有安装 chardet，默认尝试以 utf-8-sig 和 gbk
            encoding = 'utf-8-sig'
        
        # 如果无法检测到编码，默认使用 utf-8-sig
        encoding = encoding or 'utf-8-sig'

        # 解码文件内容
        decoded_content = content.decode(encoding)

        # 将文件内容重新编码为 UTF-8 并写回
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(decoded_content)

        print(f"成功将文件 {file_path} 转换为 UTF-8 编码")
    except Exception as e:
        print(f"文件 {file_path} 转换失败: {e}")

def main():
    # 获取当前目录下的所有文件
    current_dir = os.getcwd()
    for root, dirs, files in os.walk(current_dir):
        for file in files:
            file_path = os.path.join(root, file)
            convert_to_utf8(file_path)

if __name__ == "__main__":
    main()
